package com.zlp.mall.log.aspect;
import com.alibaba.fastjson.JSON;
import com.zlp.mall.core.utils.spring.SpringContextHolder;
import com.zlp.mall.log.annotation.SysLog;
import com.zlp.mall.log.event.SysLogEvent;
import com.zlp.mall.log.util.LogTypeEnum;
import com.zlp.mall.log.util.SysLogUtils;
import com.zlp.mall.upms.api.dto.req.OperLogReq;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.CodeSignature;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 操作日志使用spring event异步入库
 *
 * @author L.cm
 */
@Aspect
@Slf4j
public class SysLogAspect {

	@Around("@annotation(sysLog)")
	@SneakyThrows
	public Object around(ProceedingJoinPoint point, SysLog sysLog) {
		String strClassName = point.getTarget().getClass().getName();
		String strMethodName = point.getSignature().getName();
		log.debug("[类名]:{},[方法]:{}", strClassName, strMethodName);

        OperLogReq logVo = SysLogUtils.getSysLog();
        logVo.setTitle(sysLog.value());
        Map<String, Object> map = new HashMap<String, Object>();
        Object [] values = point.getArgs();
        String [] paramNames = ((CodeSignature) point.getSignature()).getParameterNames();
        if (Objects.nonNull(paramNames)) {
            for (int i = 0; i < paramNames.length; i++) {
                map.put(paramNames[i], values[i]);
            }
        	logVo.setParams(JSON.toJSONString(map));
        }
		// 发送异步日志事件
		Long startTime = System.currentTimeMillis();
		Object obj;

		try {
			obj = point.proceed();
		}
		catch (Exception e) {
			logVo.setType(LogTypeEnum.ERROR.getType());
			logVo.setException(e.getMessage());
			throw e;
		}
		finally {
			Long endTime = System.currentTimeMillis();
			logVo.setTime(endTime - startTime);
			SpringContextHolder.publishEvent(new SysLogEvent(logVo));
		}

		return obj;
	}

}
